<template>
  <router-layout>
    <div class="detail-box">
      <div class="wapper-box">
        <div class="content-box">
          <h2>{{data.questionnaire_title}}</h2>
          <p>{{data.questionnaire_desc}}</p>
        </div>
        <div class="question-box">
          <div class="list-box">
            <div
              class="question-list van-hairline--bottom"
              v-for="(item, index) in singles"
              :key="index"
            >
              <van-row type="flex" justify="space-between" align="center">
                <van-col>
                  <h2>{{item.questionnaire_title}}</h2>
                </van-col>
              </van-row>
              <section v-for="single in item.questionnaireOptions" :key="single.id">
                <van-radio-group v-model="singleForm[item.id]" class="demo-radio-group">
                  <van-radio :name="single">{{single.questionnaire_option}}</van-radio>
                </van-radio-group>
              </section>
            </div>
          </div>
          <!-- 多选 -->
          <div class="list-box">
            <div
              class="question-list van-hairline--bottom"
              v-for="(items, index) in doubles"
              :key="index"
            >
              <van-row type="flex" justify="space-between" align="center">
                <van-col>
                  <h2>{{items.questionnaire_title}}</h2>
                </van-col>
              </van-row>
              <section>
                <van-checkbox-group v-model="doubleForm" class="demo-checkbox-group">
                  <i v-for="(double,douIndex) in items.doubles" :key="douIndex">
                    <van-checkbox :name="double">{{ double.answer}}</van-checkbox>
                  </i>
                </van-checkbox-group>
              </section>
            </div>
          </div>
          <div class="list-box">
            <div
              class="question-list van-hairline--bottom"
              v-for="(items, index) in imports"
              :key="index"
            >
              <van-row type="flex" justify="space-between" align="center">
                <van-col>
                  <h2>{{items.questionnaire_title}}</h2>
                </van-col>
              </van-row>
              <van-cell-group>
                <van-field
                  v-model="items.message"
                  type="textarea"
                  placeholder="请输入"
                  rows="2"
                  autosize
                />
              </van-cell-group>
            </div>
          </div>
        </div>
      </div>
      <div class="base">
        <div v-if="isAnswer==0" class="base-btn" @click="save">
          <p>提交</p>
        </div>
        <div v-if="isAnswer==1" class="base-btn base-btn2">
          <p>已参与</p>
        </div>
      </div>
      <div class="popup-box" v-if="isShow">
        <div class="toast-mask" @touchmove.prevent></div>
        <!-- 提交成功时显示 -->
        <div class="bg-box" v-show="isHide" @touchmove.prevent>
          <div class="img-box"></div>
          <p class="popup-text">问卷提交成功，感谢您的参与！</p>
          <div class="toast-btn">
            <div class="toast-cancel" @click="submit">我知道了</div>
          </div>
        </div>
        <!-- 提交失败时显示 -->
        <div class="bg-box" v-show="isError" @touchmove.prevent>
          <div class="img-box no-finish"></div>
          <p class="popup-text">题目未完成，请继续答题</p>
          <div class="toast-btn">
            <div class="toast-cancel continue" @click="isShow=false,isError=false">继续答题</div>
          </div>
        </div>
      </div>
    </div>
  </router-layout>
</template>
<script>
import {
  servey_findById,
  servey_save,
  servey_addBrowseNum
} from "@/api/survey";
import moment from "moment";
import TitleItem from "../../components/public/title/title";
 import { Debounce, Throttle } from "@/utils";

export default {
  name: "SurveyDetails",
  components: { TitleItem },
  data() {
    return {
      List: "",
      isShow: false,
      isAnswer: null, //是否已提交
      isHide: false, //成功显示
      isError: false, //失败显示
      question_type: "", //1是单选，2是多选 3评分 4输入
      data: {},
      answer_starttime: "", //答题开始时间
      answer_time: "", //答题总时间
      singleForm: {}, //单选缓存对象
      doubleForm: [], //多选框缓存对象
      singles: [], //单选
      doubles: [], //多选
      imports: [], //输入
      cacheForm: [],
      radio: "1"
    };
  },
  filters: {
    formate_date(v) {
      return moment(v).format("YYYY/MM/DD");
    }
  },
  methods: {
    selected: function(items, index) {},
    save:Throttle(function() {
      let end = new Date();
      let total_time = end.getTime() - this.newDate.getTime();
      total_time = Math.ceil(total_time / 1000);
      this.answer_time = total_time;
      this.cacheForm = [];
      //格式化 单选
      for (const key in this.singleForm) {
        if (this.singleForm.hasOwnProperty(key)) {
          const single = this.singleForm[key];
          this.cacheForm.push({
            key: key,
            questionnaire_qesid: single.questionnaire_qesid,
            questionnaire_optionid: single.id,
            answer: single.questionnaire_option
          });
        }
      }
      //   格式化输入框
      this.imports.map(item => {
        item.questionnaireOptions.forEach(it => {
          this.cacheForm.push({
            questionnaire_qesid: it.questionnaire_qesid,
            questionnaire_optionid: it.id, //可不要
            answer: item.message
          });
        });
      });
      //格式化 多选
      this.doubleForm.forEach(item => {
        this.cacheForm.push({
          key: item.questionnaire_qesid,
          ...item
        });
      });
      if (this.cacheForm.length < this.data.questionnaireQess.length) {
        this.isShow = true;
        this.isError = true;
        return;
      }
      // this.isShow = true;
      // this.isHide = true;
      this.fromData();
    },1000),
    submit() {
      this.isShow = false;
      this.isHide = false;
      // this.fromData();
    },
    async fromData() {
      try {
        let par = {
          questionnaire_id: this.$route.query.id,
          answer_starttime: this.answer_starttime,
          answer_time: this.answer_time,
          questionnaireAnss: JSON.stringify(this.cacheForm)
        };
        let res = await servey_save(par);
        if (res.data.status == 100) {
          this.isShow = true;
          this.isHide = true;
          this.message = "";
          // this.$router.push("/SurveryList");
          this.initList();
        }
      } catch (error) {
        if (error.data.status == 101) {
          this.$toast(error.data.msg || "您已提交过问卷,不能重复提交");
        }
      }
    },
    //一次阅读
    async oneBrowse() {
      let query = Object.assign(
        { id: this.$route.query.id },
        { company_id: localStorage.getItem("companyId") - 0 }
      );
      let res = await servey_addBrowseNum(query);
      let result = res.data;
      if (result.status == 100) {
      } else {
      }
    },
    async initList() {
      let par = {
        id: this.$route.query.id
      };
      let query = Object.assign({}, par);
      let { data } = await servey_findById(query);
      this.data = data.data;
      this.singles = [];
      this.isAnswer = data.data.isanswer;
      this.singles = data.data.questionnaireQess.filter(item => {
        if (item.question_type === 1) {
          return item;
        }
      });

      //初始化 doubles
      /****
         * questionnaire_qesid: single.questionnaire_qesid,
            questionnaire_optionid: single.id,
            answer: single.questionnaire_option
         */
      this.doubles = [];
      data.data.questionnaireQess.forEach(item => {
        if (item.question_type === 2) {
          this.doubles.push({
            questionnaire_title: item.questionnaire_title,
            doubles: item.questionnaireOptions.map(dou => {
              return {
                questionnaire_qesid: dou.questionnaire_qesid,
                questionnaire_optionid: dou.id,
                answer: dou.questionnaire_option
              };
            })
          });
        }
      });
      this.imports = [];
      this.imports = data.data.questionnaireQess.filter(item => {
        if (item.question_type === 4) {
          return item;
        }
      });
    }
  },
  created() {
    this.answer_starttime = moment().format("YYYY-MM-DD HH:mm:ss");
    this.newDate = new Date();
    this.initList();
    this.oneBrowse();
  }
};
</script>
<style lang="scss" scoped>
@import "SurveyDetails";
</style>

